const router = require('koa-router')()
const Koa = require('koa')
const app = new Koa()
const connection = require('./db'); // 导入数据库连接对象
const fs = require('fs');
// 配置koa-body处理文件上传
/*router.use((req, res, next) => {
  const authHeader = req.headers.authorization;
  if (authHeader) {
    const token = authHeader.split(' ')[1];
    jwt.verify(token, 'secret', (err, payload) => {
      if (err) {
        return res.status(401).json({ message: 'token 不正确' });
      }
      req.user = payload;
      next();
    });
  } else {
    res.status(401).json({ message: '未提供 token' });
  }
});*/

router.post('/upload', async (ctx, next) => {
    console.log(111);
    ctx.body = "success";
    const allfiles = await getFiles('routes/uploads'); // 获取目录下文件列表
    console.log(allfiles);
    const DELETE = 'delete from imagelist'
    connection.query(DELETE, (err, result) => {
      if (err) return err;
      console.log("result", result);
  });
    for (const image of allfiles) {
      const sql = `INSERT INTO imagelist (path, size, type) VALUES (?, ?, ?)`;
      const params = [image.path, image.size, image.type];
       connection.query(sql, params);
    }
  
  });
router.get('/upload', function (ctx, next) {
    ctx.body = 'this is a upload!'
  });
    // 实现getFiles函数，使用fs模块遍历目录并返回文件列表
async function getFiles(dirPath) {
  const files = [];
  const dir = await fs.promises.opendir(dirPath);
  for await (const dirent of dir) {
  
    const urls = `${dirent.name}`
    const filepath = `${dirPath}/${dirent.name}`;
    const stats = await fs.promises.stat(filepath);  
    if (getFileType(filepath)!='file') {
    const file = {
      path: urls,
      size: stats.size,
      type: getFileType(filepath)
    };
    files.push(file);}

  }
  return files;
}
// 获取文件类型
function getFileType(filepath) {
  const ext = filepath.split('.').pop().toLowerCase();
  switch (ext) {
    case 'jpg':
      return 'jpg';
    case 'jpeg':
      return 'jpeg';
    case 'png':
      return 'png';
    default:
      return 'file';
  }
}

module.exports = router